<?php

class company extends ActiveRecord {
    /**
     * The followings are the available columns in table 'customer':
     * @var string $cname
     * @var string $address
     * @var string $tele
     * @var string $fax
     * @var string $pic
     * @var integer $id
     * @var string $email
     * @var integer $postal
     * @var integer $date_added
     * @var integer $country_code
     */

    /**
     * Returns the static model of the specified AR class.
     * @return CActiveRecord the static model class
     */
    public $shipper_id = null, $searchText;
    public $AddressString, $ContactString, $EmailString;

    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'company';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        return array(
            array('cname', 'length', 'max' => 250),
            array('domain', 'length', 'max' => 1024),
            array('cname', 'unique', 'allowEmpty' => false, 'caseSensitive' => false),
            array('cname, domain', 'required'),
            array('cname, address, contacts, searchText', 'safe', 'on' => 'search'),
        //array('id','numerical', 'integerOnly'=>true),
        );
    }

    public function beforeValidate() {
        $this->domain = Yii::app()->session->get('domain');
        return parent::beforeValidate();
    }

    public function beforeFind() {
        $this->domain = Yii::app()->session->get('domain');
        return parent::beforeFind();
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'address' => array(self::HAS_MANY, 'company_address', 'company_id'),
            'members' => array(self::HAS_MANY, 'company_members', 'company_id'),
            'email' => array(self::HAS_MANY, 'company_email', 'company_id'),
            'cargo' => array(self::HAS_MANY, 'cargo', 'shipper_id', 'limit' => 5)
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function returnPhone($string = true) {
        if ($this->isNewRecord)
            return '-';
    }

    public function afterFind() {
        if ($this->getScenario() == 'update') {
            if (count($this->address) == 0)
                $this->address = array(new company_address);

            if (count($this->email) == 0)
                $this->email = array(new company_email);
        }
        return parent::afterFind();
    }

    public function getIDbyName($name) {
        if (empty($name))
            return false;
        $criteria = new CDbCriteria;
        $criteria->condition = "cname REGEXP '^:cname.{6}$'";
        $criteria->params = array(':cname' => $name);
        $result = $this->findAll($criteria);
        if (!$result)
            return false;
        if (count($result) > 1)
            return 0;
        return $result[0]->cname;
    }

    public function getAddress($type=null) {
        $address = '';
        if ($type != '' && $type != null) 
            $model = company_address::model()->find('type like :type AND company_id = :company_id', array(':type' => $type, ':company_id' => $this->id));
        else
            $model = company_address::model()->find('company_id=:company_id',array(':company_id'=>$this->id));
        if ($model != null)
                $address = '(' . $model->type . ')' . $model->address;
        if ($address == '' && count($this->address) > 0)
            $address = '(' . $this->address[0]->type . ')' . $this->address[0]->address;
        return $address;
    }

    public function getContact($type) {
        $contact = '';
        if ($type != '' && $type != null) {
            $model = company_address::model()->find('type like :type and company_id = :company_id', array(':type' => $type, ':company_id' => $this->id));
            if ($model != null)
                $contact = $model->getRef('contacts');
        }
        if ($contact == '' && count($this->address[0]->contacts) > 0)
            $contact = $this->address[0]->getRef('contacts');
        return $contact;
    }

    public function getInfo($id=null) {
        $model = $this->with(array('address', 'contacts', 'members', 'members.member_contacts'))->findByPk($id);
        foreach ($model->address() as $add) {
            $address[] = array('type' => $add->type, 'address' => $add->address, 'id' => $add->id);
        }
        $_contact = array();
        foreach ($model->members() as $member) {
            foreach ($member->member_contacts as $contact) {
                $_contact[] = array('type' => $contact->type, 'ref' => $contact->ref, 'id' => $contact->id, 'name' => $member->name);
            }
        }
        foreach ($model->contacts() as $contact) {
            $_contact[] = array('type' => '', 'ref' => $contact->ref, 'id' => $contact->id, 'name' => $contact->type);
        }
        $returndata = array('cname' => $model->cname, 'address' => $address, 'contact' => $_contact);
        return $returndata;
        /* if($id==null)
          return array();
          $db = $this->dbConnection;
          $criteria = new CDbCriteria;
          $criteria->condition = 'id = :id';
          $criteria->params = array(':id'=>$id);
         */
    }

    public function attributeLabels() {
        return array(
            'cname' => 'Company name',
        );
    }

    public function getNameByID($companyID) {
        $this->findByPk($companyID);
    }

    public function search() {
        $criteria = new CDbCriteria;
        $criteria->compare('cname', $this->searchText, true, 'OR');
        $criteria->compare('id', $this->searchText, true, 'OR');
        //$criteria->compare('id',$this->id, false,'OR');
        $criteria->compare('cname', $this->cname, true, 'OR');
        return new CActiveDataProvider(get_class($this), array(
            'criteria' => $criteria,
            'pagination' => array(
                'pageSize' => 20,
            ),
        ));
    }

    public function supplier_history() {
        $criteria = new CDbCriteria;
        $criteria->compare('shipper_id', $this->id);
        return new CActiveDataProvider('cargo', array(
            'criteria' => $criteria,
        ));
    }

    public function buyer_history() {
        $criteria = new CDbCriteria;
        $criteria->compare('consignee_id', $this->id);
        return new CActiveDataProvider('cargo', array(
            'criteria' => $criteria,
        ));
    }

}